//
//  AppInfoViewController.m
//  DualMediationDemo
//
//  应用信息界面控制器实现
//  显示广告配置、广告策略和内购商品信息
//

#import "AppInfoViewController.h"
#import <Foundation/Foundation.h>
#import "DualMediationSDKPublic.h"
#import "DMConfigReader.h"
#import <Masonry/Masonry.h>

@interface AppInfoViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) UISegmentedControl *segmentedControl;
@property (nonatomic, strong) NSDictionary *rawConfigData; // 原始配置数据（用于读取secondad_unitID）

@end

@implementation AppInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    [self loadData];
}

#pragma mark - UI Setup

- (void)setupUI {
    self.view.backgroundColor = [UIColor systemBackgroundColor];
    self.title = @"应用信息";
    
    // 创建导航栏右侧刷新按钮
    UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
                                                                                   target:self
                                                                                   action:@selector(refreshData)];
    self.navigationItem.rightBarButtonItem = refreshButton;
    
    // 创建分段控制器
    [self createSegmentedControl];
    
    // 创建表格视图
    [self createTableView];
    
    // 设置约束
    [self setupConstraints];
}

- (void)createSegmentedControl {
    NSArray *items = @[@"广告配置", @"应用配置", @"内购商品"];
    self.segmentedControl = [[UISegmentedControl alloc] initWithItems:items];
    self.segmentedControl.selectedSegmentIndex = 0;
    [self.segmentedControl addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.segmentedControl];
}

- (void)createTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.backgroundColor = [UIColor systemBackgroundColor];
    [self.view addSubview:self.tableView];
}

- (void)setupConstraints {
    [self.segmentedControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop).offset(16);
        make.left.equalTo(self.view).offset(16);
        make.right.equalTo(self.view).offset(-16);
        make.height.mas_equalTo(32);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.segmentedControl.mas_bottom).offset(16);
        make.left.right.bottom.equalTo(self.view);
    }];
}

#pragma mark - Data Loading

- (void)loadData {
    self.dataSource = [[NSMutableArray alloc] init];
    // 预读取原始配置（用于显示备用广告位ID）
    [self loadRawConfigIfNeeded];
    
    switch (self.segmentedControl.selectedSegmentIndex) {
        case 0:
            [self loadAdConfigData];
            break;
        case 1:
            [self loadAdStrategyData];
            break;
        case 2:
            [self loadIAPData];
            break;
        default:
            break;
    }
    
    [self.tableView reloadData];
}

#pragma mark - Raw Config

- (void)loadRawConfigIfNeeded {
    if (self.rawConfigData) { return; }
    NSString *path = [[DMConfigReader sharedInstance] configFilePath];
    if (!path || path.length == 0) { return; }
    NSData *data = [NSData dataWithContentsOfFile:path];
    if (!data) { return; }
    id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    if ([json isKindOfClass:[NSDictionary class]]) {
        self.rawConfigData = (NSDictionary *)json;
    }
}

- (NSString *)secondaryIdForGroup:(NSString *)group sdkType:(NSString *)sdkType isLow:(BOOL)isLow {
    // group: BannerIds / InterIds / SplashIds / RewardIds / NativeIds
    NSDictionary *adConfig = self.rawConfigData[@"ad_config"];
    if (![adConfig isKindOfClass:[NSDictionary class]]) return @"";
    NSArray *arr = adConfig[group];
    if (![arr isKindOfClass:[NSArray class]]) return @"";
    for (NSDictionary *item in arr) {
        if (![item isKindOfClass:[NSDictionary class]]) continue;
        NSString *t = item[@"ad_type"] ?: @"";
        BOOL low = [item[@"is_low"] boolValue];
        if ([t isEqualToString:sdkType] && low == isLow) {
            NSString *sec = item[@"secondad_unitID"];
            return sec ? : @"";
        }
    }
    return @"";
}

- (void)loadAdConfigData {
    DMConfigReader *configReader = [DMConfigReader sharedInstance];
    
    // 基础配置信息
    NSMutableDictionary *basicSection = [[NSMutableDictionary alloc] init];
    basicSection[@"title"] = @"基础配置";
    NSMutableArray *basicItems = [[NSMutableArray alloc] init];
    
    NSString *appName = [configReader appName] ?: @"未配置";
    [basicItems addObject:@{@"key": @"应用名称", @"value": appName}];
    [basicItems addObject:@{@"key": @"包名", @"value": [configReader packageName] ?: @"未配置"}];
    [basicItems addObject:@{@"key": @"SDK版本", @"value": [[DualMediationSDKPublic sharedInstance] sdkVersion] ?: @"未知"}];
    [basicItems addObject:@{@"key": @"SDK版本", @"value": [configReader sdkVersion]}];
    [basicItems addObject:@{@"key": @"默认SDK类型", @"value": [configReader defaultSDKType] ?: @"未配置"}];
    
    basicSection[@"items"] = basicItems;
    [self.dataSource addObject:basicSection];
    
    // 广告单元配置
    NSMutableDictionary *adUnitsSection = [[NSMutableDictionary alloc] init];
    adUnitsSection[@"title"] = @"广告单元配置";
    NSMutableArray *adUnitsItems = [[NSMutableArray alloc] init];
    
    // Banner广告配置
    NSArray *bannerConfigs = [configReader bannerAdConfigs];
    for (DMAdUnitConfig *config in bannerConfigs) {
        NSString *showPrefix = [NSString stringWithFormat:@"Banner-%@", config.ad_type ?: @"-"];
        [adUnitsItems addObject:@{ @"key": [showPrefix stringByAppendingString:@" 主"],
                                   @"value": config.ad_unitID ?: @"未配置" }];
        NSString *sec = [self secondaryIdForGroup:@"BannerIds" sdkType:config.ad_type isLow:config.is_low];
        if (sec.length > 0) {
            [adUnitsItems addObject:@{ @"key": [showPrefix stringByAppendingString:@" 备"],
                                       @"value": sec }];
        }
    }
    
    // 激励视频广告配置
    NSArray *rewardConfigs = [configReader rewardedAdConfigs];
    for (DMAdUnitConfig *config in rewardConfigs) {
        NSString *showPrefix = [NSString stringWithFormat:@"激励视频-%@", config.ad_type ?: @"-"];
        [adUnitsItems addObject:@{ @"key": [showPrefix stringByAppendingString:@" 主"],
                                   @"value": config.ad_unitID ?: @"未配置" }];
        NSString *sec = [self secondaryIdForGroup:@"RewardIds" sdkType:config.ad_type isLow:config.is_low];
        if (sec.length > 0) {
            [adUnitsItems addObject:@{ @"key": [showPrefix stringByAppendingString:@" 备"],
                                       @"value": sec }];
        }
    }
    
    // 插屏广告配置
    NSArray *interConfigs = [configReader interstitialAdConfigs];
    for (DMAdUnitConfig *config in interConfigs) {
        NSString *showPrefix = [NSString stringWithFormat:@"插屏-%@", config.ad_type ?: @"-"];
        [adUnitsItems addObject:@{ @"key": [showPrefix stringByAppendingString:@" 主"],
                                   @"value": config.ad_unitID ?: @"未配置" }];
        NSString *sec = [self secondaryIdForGroup:@"InterIds" sdkType:config.ad_type isLow:config.is_low];
        if (sec.length > 0) {
            [adUnitsItems addObject:@{ @"key": [showPrefix stringByAppendingString:@" 备"],
                                       @"value": sec }];
        }
    }
    
    // 开屏广告配置
    NSArray *splashConfigs = [configReader splashAdConfigs];
    for (DMAdUnitConfig *config in splashConfigs) {
        NSString *showPrefix = [NSString stringWithFormat:@"开屏-%@", config.ad_type ?: @"-"];
        [adUnitsItems addObject:@{ @"key": [showPrefix stringByAppendingString:@" 主"],
                                   @"value": config.ad_unitID ?: @"未配置" }];
        NSString *sec = [self secondaryIdForGroup:@"SplashIds" sdkType:config.ad_type isLow:config.is_low];
        if (sec.length > 0) {
            [adUnitsItems addObject:@{ @"key": [showPrefix stringByAppendingString:@" 备"],
                                       @"value": sec }];
        }
    }
    
    // 原生广告配置
    NSArray *nativeConfigs = [configReader nativeAdConfigs];
    for (DMAdUnitConfig *config in nativeConfigs) {
        NSString *showPrefix = [NSString stringWithFormat:@"原生-%@", config.ad_type ?: @"-"];
        [adUnitsItems addObject:@{ @"key": [showPrefix stringByAppendingString:@" 主"],
                                   @"value": config.ad_unitID ?: @"未配置" }];
        NSString *sec = [self secondaryIdForGroup:@"NativeIds" sdkType:config.ad_type isLow:config.is_low];
        if (sec.length > 0) {
            [adUnitsItems addObject:@{ @"key": [showPrefix stringByAppendingString:@" 备"],
                                       @"value": sec }];
        }
    }
    
    adUnitsSection[@"items"] = adUnitsItems;
    [self.dataSource addObject:adUnitsSection];
    
    // SDK密钥配置
    NSMutableDictionary *sdkKeysSection = [[NSMutableDictionary alloc] init];
    sdkKeysSection[@"title"] = @"SDK密钥";
    NSMutableArray *sdkKeysItems = [[NSMutableArray alloc] init];
    
    [sdkKeysItems addObject:@{@"key": @"IronSource AppKey", @"value": [configReader ironSourceAppKey] ?: @"未配置"}];
    [sdkKeysItems addObject:@{@"key": @"MAX SDK Key", @"value": [configReader maxAppKey] ?: @"未配置"}];
    
    sdkKeysSection[@"items"] = sdkKeysItems;
    [self.dataSource addObject:sdkKeysSection];
}

- (void)loadAdStrategyData {
    DMConfigReader *configReader = [DMConfigReader sharedInstance];
    
    // 应用配置摘要
    NSMutableDictionary *strategySection = [[NSMutableDictionary alloc] init];
    strategySection[@"title"] = @"应用配置";
    NSMutableArray *strategyItems = [[NSMutableArray alloc] init];
    
    // 显示实际的广告策略配置
    [strategyItems addObject:@{@"key": @"默认SDK类型", @"value": [configReader defaultSDKType] ?: @"未配置"}];
    [strategyItems addObject:@{@"key": @"SDK版本", @"value": [configReader sdkVersion]}];
    
    // 显示各类型广告配置数量
    NSArray *bannerConfigs = [configReader bannerAdConfigs];
    NSArray *rewardConfigs = [configReader rewardedAdConfigs];
    NSArray *interConfigs = [configReader interstitialAdConfigs];
    NSArray *splashConfigs = [configReader splashAdConfigs];
    NSArray *nativeConfigs = [configReader nativeAdConfigs];
    
    [strategyItems addObject:@{@"key": @"Banner广告配置", @"value": [NSString stringWithFormat:@"%lu个", (unsigned long)bannerConfigs.count]}];
    [strategyItems addObject:@{@"key": @"激励视频配置", @"value": [NSString stringWithFormat:@"%lu个", (unsigned long)rewardConfigs.count]}];
    [strategyItems addObject:@{@"key": @"插屏广告配置", @"value": [NSString stringWithFormat:@"%lu个", (unsigned long)interConfigs.count]}];
    [strategyItems addObject:@{@"key": @"开屏广告配置", @"value": [NSString stringWithFormat:@"%lu个", (unsigned long)splashConfigs.count]}];
    [strategyItems addObject:@{@"key": @"原生广告配置", @"value": [NSString stringWithFormat:@"%lu个", (unsigned long)nativeConfigs.count]}];
    
    strategySection[@"items"] = strategyItems;
    [self.dataSource addObject:strategySection];
    
    // Info.plist 信息
    NSDictionary *info = [[NSBundle mainBundle] infoDictionary];
    if ([info isKindOfClass:[NSDictionary class]]) {
        NSMutableDictionary *plistSection = [[NSMutableDictionary alloc] init];
        plistSection[@"title"] = @"Info.plist";
        NSMutableArray *plistItems = [[NSMutableArray alloc] init];

        NSString *bundleName = info[@"CFBundleDisplayName"] ?: info[@"CFBundleName"] ?: @"-";
        NSString *bundleId = info[@"CFBundleIdentifier"] ?: @"-";
        NSString *shortVer = info[@"CFBundleShortVersionString"] ?: @"-";
        NSString *buildVer = info[@"CFBundleVersion"] ?: @"-";
        NSString *minOS = info[@"MinimumOSVersion"] ?: @"-";

        // URL Schemes
        NSMutableArray *schemes = [NSMutableArray array];
        NSArray *urlTypes = info[@"CFBundleURLTypes"];
        if ([urlTypes isKindOfClass:[NSArray class]]) {
            for (NSDictionary *t in urlTypes) {
                NSArray *arr = t[@"CFBundleURLSchemes"];
                if ([arr isKindOfClass:[NSArray class]]) {
                    for (id s in arr) { if ([s isKindOfClass:[NSString class]]) [schemes addObject:s]; }
                }
            }
        }
        NSString *schemesStr = schemes.count ? [schemes componentsJoinedByString:@", "] : @"-";

        // 查询白名单
        NSArray *queriesSchemes = info[@"LSApplicationQueriesSchemes"];
        NSString *queriesStr = ([queriesSchemes isKindOfClass:[NSArray class]] && queriesSchemes.count)
            ? [NSString stringWithFormat:@"%lu个", (unsigned long)queriesSchemes.count]
            : @"-";

        // 后台模式
        NSArray *bgModes = info[@"UIBackgroundModes"];
        NSString *bgModesStr = ([bgModes isKindOfClass:[NSArray class]] && bgModes.count)
            ? [bgModes componentsJoinedByString:@", "]
            : @"-";

        [plistItems addObject:@{ @"key": @"Bundle Name", @"value": bundleName }];
        [plistItems addObject:@{ @"key": @"Bundle ID", @"value": bundleId }];
        [plistItems addObject:@{ @"key": @"版本号", @"value": shortVer }];
        [plistItems addObject:@{ @"key": @"构建号", @"value": buildVer }];
        [plistItems addObject:@{ @"key": @"最低系统", @"value": minOS }];
        [plistItems addObject:@{ @"key": @"URL Schemes", @"value": schemesStr }];
        [plistItems addObject:@{ @"key": @"Queries Schemes", @"value": queriesStr }];
        [plistItems addObject:@{ @"key": @"后台模式", @"value": bgModesStr }];

        plistSection[@"items"] = plistItems;
        [self.dataSource addObject:plistSection];
    }

    // 第三方服务配置
    NSMutableDictionary *servicesSection = [[NSMutableDictionary alloc] init];
    servicesSection[@"title"] = @"第三方服务";
    NSMutableArray *servicesItems = [[NSMutableArray alloc] init];
    
    // TA配置
    DMTAConfig *taConfig = [configReader taConfig];
    if (taConfig) {
        [servicesItems addObject:@{@"key": @"TA服务器", @"value": taConfig.server_url ?: @"未配置"}];
        [servicesItems addObject:@{@"key": @"TA AppID", @"value": taConfig.app_id ?: @"未配置"}];
    }
    
    // Adjust配置
    DMAdjustConfig *adjustConfig = [configReader adjustConfig];
    if (adjustConfig) {
        [servicesItems addObject:@{@"key": @"Adjust Token", @"value": adjustConfig.app_token ?: @"未配置"}];
    }
    
    // Facebook配置
    DMFBConfig *fbConfig = [configReader fbConfig];
    if (fbConfig) {
        [servicesItems addObject:@{@"key": @"Facebook AppID", @"value": fbConfig.facebook_AppId ?: @"未配置"}];
    }
    
    servicesSection[@"items"] = servicesItems;
    [self.dataSource addObject:servicesSection];
}

- (void)loadIAPData {
    DMConfigReader *configReader = [DMConfigReader sharedInstance];
    
    // 消耗品
    NSArray<DMIAPProductConfig *> *consumables = [configReader consumableProducts];
    if (consumables && consumables.count > 0) {
        NSMutableDictionary *consumablesSection = [[NSMutableDictionary alloc] init];
        consumablesSection[@"title"] = @"消耗品";
        NSMutableArray *consumablesItems = [[NSMutableArray alloc] init];
        
        for (DMIAPProductConfig *product in consumables) {
            [consumablesItems addObject:@{
                @"key": product.productId ?: @"未知商品",
                @"value": [NSString stringWithFormat:@"$%@", product.dollar_price ?: @"0.00"]
            }];
        }
        
        consumablesSection[@"items"] = consumablesItems;
        [self.dataSource addObject:consumablesSection];
    }
    
    // 非消耗品
    NSArray<DMIAPProductConfig *> *nonConsumables = [configReader nonConsumableProducts];
    if (nonConsumables && nonConsumables.count > 0) {
        NSMutableDictionary *nonConsumablesSection = [[NSMutableDictionary alloc] init];
        nonConsumablesSection[@"title"] = @"非消耗品";
        NSMutableArray *nonConsumablesItems = [[NSMutableArray alloc] init];
        
        for (DMIAPProductConfig *product in nonConsumables) {
            [nonConsumablesItems addObject:@{
                @"key": product.productId ?: @"未知商品",
                @"value": [NSString stringWithFormat:@"$%@", product.dollar_price ?: @"0.00"]
            }];
        }
        
        nonConsumablesSection[@"items"] = nonConsumablesItems;
        [self.dataSource addObject:nonConsumablesSection];
    }
    
    // 订阅商品
    NSArray<DMIAPProductConfig *> *subscriptions = [configReader subscriptionProducts];
    if (subscriptions && subscriptions.count > 0) {
        NSMutableDictionary *subscriptionsSection = [[NSMutableDictionary alloc] init];
        subscriptionsSection[@"title"] = @"订阅商品";
        NSMutableArray *subscriptionsItems = [[NSMutableArray alloc] init];
        
        for (DMIAPProductConfig *product in subscriptions) {
            [subscriptionsItems addObject:@{
                @"key": product.productId ?: @"未知商品",
                @"value": [NSString stringWithFormat:@"$%@", product.dollar_price ?: @"0.00"]
            }];
        }
        
        subscriptionsSection[@"items"] = subscriptionsItems;
        [self.dataSource addObject:subscriptionsSection];
    }
    
    // 如果没有任何内购商品配置
    if (self.dataSource.count == 0) {
        NSMutableDictionary *emptySection = [[NSMutableDictionary alloc] init];
        emptySection[@"title"] = @"内购商品";
        NSMutableArray *emptyItems = [[NSMutableArray alloc] init];
        [emptyItems addObject:@{@"key": @"状态", @"value": @"未配置内购商品"}];
        emptySection[@"items"] = emptyItems;
        [self.dataSource addObject:emptySection];
    }
}

#pragma mark - Actions

- (void)segmentChanged:(UISegmentedControl *)sender {
    [self loadData];
}

- (void)refreshData {
    // 重新加载配置
    [[DMConfigReader sharedInstance] reloadConfig];
    [self loadData];
    
    // 显示刷新提示
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"刷新完成"
                                                                   message:@"配置信息已更新"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSDictionary *sectionData = self.dataSource[section];
    NSArray *items = sectionData[@"items"];
    return items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"InfoCell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"InfoCell"];
    }
    
    NSDictionary *sectionData = self.dataSource[indexPath.section];
    NSArray *items = sectionData[@"items"];
    NSDictionary *item = items[indexPath.row];
    
    cell.textLabel.text = item[@"key"];
    cell.detailTextLabel.text = item[@"value"];
    cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    
    // 设置字体
    cell.textLabel.font = [UIFont systemFontOfSize:16];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:14];
    cell.detailTextLabel.textColor = [UIColor systemGrayColor];
    
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSDictionary *sectionData = self.dataSource[section];
    return sectionData[@"title"];
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    // 获取选中的数据
    NSDictionary *sectionData = self.dataSource[indexPath.section];
    NSArray *items = sectionData[@"items"];
    NSDictionary *item = items[indexPath.row];
    
    // 如果当前在“内购商品”页签，则点击即发起对应商品的购买
    if (self.segmentedControl.selectedSegmentIndex == 2) {
        NSString *productId = item[@"key"];
        // 过滤掉占位项
        if (productId.length > 0 && ![productId isEqualToString:@"状态"]) {
            [[DualMediationSDKPublic sharedInstance] launchInAppPurchase:productId];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"已发起购买"
                                                                           message:[NSString stringWithFormat:@"商品ID: %@", productId]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
            [self presentViewController:alert animated:YES completion:nil];
            return;
        }
    }
    
    // 复制到剪贴板
    NSString *copyText = [NSString stringWithFormat:@"%@: %@", item[@"key"], item[@"value"]];
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = copyText;
    
    // 显示复制提示
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"已复制"
                                                                   message:copyText
                                                            preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:nil];
}

@end
